var rootPath = getRootPath();
$(function() {
	var oripid = $("#oripid").val();

	$.ajax({
		url : rootPath + '/category/pid/0', // 父级pid都为0
		type : 'GET',
		success : function(data) {
			if (data.returnCode == "0000") {
				var length = data.returnObject.length;
				$("#selectPid").html(length);
				var option = "";
				option += "<option value=\"" + oripid + "\">不移动</option>"
				for (var i = 0; i < length; i++) {
					option += "<option value =\""
							+ data.returnObject[i].categoryId + "\">"
							+ data.returnObject[i].title + "</option>";
				}
				$("#selectPid").append(option);
			} else {
				layer.alert(data.returnMessage);
			}
		},
		error : function(jqXHR, textStatus, errorThrown) {
			layer.alert("error:(");
		}

	});

	jQuery.validator.addMethod("checkTitle", function(value, element) {
		var oriTitle = $("#oriTitle").val();
		return checkTitle(value, oriTitle);
	}, "类别名称已存在");

	$("#categoryEditForm").validate({
		rules : {
			title : {
				required : true,
				checkTitle : true
			}
		},
		onkeyup : false,
		focusCleanup : true,
		success : "valid",
		submitHandler : function(form) {
			var categoryId = $("#categoryId").val();
			$.ajax({
				url : rootPath + '/category/' + categoryId,
				type : 'PUT',
				data : JSON.stringify($('#categoryEditForm').serializeJson()),
				contentType : 'application/json;charset=UTF-8',
				success : function(data) {
					if (data.returnCode == "0000") {
						layer.msg('成功更新资源!', {icon : 1,time : 1000}, function() {
							parent.window.location.href = rootPath + '/categoryPage';
							var index = parent.layer.getFrameIndex(window.name);
							parent.layer.close(index);
						});
					} else {
						layer.alert(data.returnMessage);
					}
				},
				error : function(jqXHR, textStatus, errorThrown) {
					layer.alert("更新资源失败:(");
				}
			});
		}
	});
});

function checkTitle(title, oriTitle) {
	var isValidName = true;
	if (title != oriTitle) {
		$.ajax({
			url : rootPath + '/category/checkCategoryTitle',
			type : 'GET',
			async : false,
			data : {
				"title" : title
			},
			success : function(data) {
				if (data != "true") {
					isValidName = false;
				}
			},
			error : function(jqXHR, textStatus, errorThrown) {
				layer.alert("error:(");
			}
		});
	}
	return isValidName;
}